<?php

namespace App\Api\Controllers\HuiPay;


use App\Api\Controllers\Config\HuiPayConfigController;
use function EasyWeChat\Kernel\Support\get_client_ip;
use function EasyWeChat\Kernel\Support\get_server_ip;
use Illuminate\Support\Facades\Log;

class PayController extends BaseController
{
    //b_2_c扫 0-系统错误 1-成功 2-正在支付 3-失败
    public function scan_pay($data)
    {
        try {
            $out_trade_no = $data['out_trade_no'] ?? '';
            $total_amount = $data['total_amount'] ?? '';
            $remark = $data['remark'] ?? '';
            $device_id = $data['device_id'] ?? '';
            $shop_name = $data['shop_name'] ?? '';
            $notify_url = $data['notify_url'] ?? ''; //交易回调地址
            $url = $data['request_url'] ?? '';
            $payType = $data['pay_type'] ?? '';
            $payWay = $data['pay_way'] ?? '';
            $mer_cust_id = $data['mer_cust_id'] ?? ''; //商户客户号
            $user_cust_id = $data['user_cust_id'] ?? ''; //用户客户号
            $orgId = $data['org_id'] ?? '';
            $private_key = $data['private_key'] ?? '';
            $public_key = $data['public_key'] ?? '';
            $open_id = $data['open_id'] ?? '';
            $code = $data['code'] ?? '';
            $merchant_id = $data['merchant_id'] ?? '';

            $sign_data = [
                'api_version' => '20', //可选,版本号,目前固定为20
                'cust_id' => $user_cust_id, //用户客户号
                'order_id' => $out_trade_no, //订单号,由机具或商户生成，必须保证唯一，50位内的字母或数字组合
                'device_id' => $device_id, //机具号
                'trans_amt' => number_format($total_amount, 2), //交易金额,泛指交易金额，金额格式必须是###.00，比如2.00，2.01
                'auth_code' => $code, //二维码
                'ip_addr' => get_client_ip(), //ip地址
                'oper_user_id' => $merchant_id, //可选,操作员
                'goods_desc' => $shop_name, //可选,商品描述
                'os_version' => '', //可选,操作系统版本
                'soft_version' => '', //可选,软件版本
                'longitude' => '', //可选,经度
                'latitude' => '', //可选,纬度
                'imei' => '', //可选,imei
                'mac_ip' => '', //可选,Mac地址
                'base_station_info' => '', //可选,基站信息
                'bg_ret_url' => $notify_url, //可选,交易结果通知地址,不传则不通知,接口同步返回不通知
                'mer_priv' => '', //可选,商户私有域,为商户的自定义字段，该字段在交易完成后由本平台原样返回
                'extension' => '', //可选,扩展域,用于扩展请求参数
                'hb_fq_num' => '', //可选,用户花呗分期数,支付宝花呗分期分期数，暂时只支持3、6、12
            ];
            $post_data = [
                'data'=> $sign_data,
                'sign_type'=> 'RSA2',
                'mer_cust_id'=> $mer_cust_id,
                'source_num'=> $orgId
            ];

            $re = $this->execute($url, $post_data, $sign_data, $private_key, $public_key);
            //系统错误
            if ($re['status'] === '0') {
                return $re;
            }

            //业务成功
            if ($re['status'] == "000000") {
                $return_json = json_decode($re['data'], true);
                //交易成功
                return [
                    'status' => 1,
                    'message' => '成功',
                    'data' => $return_json,
                ];
            } elseif ($re['status'] == "000001"){
                $return_json = json_decode($re['data'], true);
                //处理中
                return [
                    'status' => 2,
                    'message' => '处理中',
                    'data' => $return_json,
                ];
            } else {
                //失败
                return [
                    'status' => 0,
                    'message' => $re['message']
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }


    //c_2_b扫 0-系统错误 1-成功 2-处理中 3-失败
    public function qr_submit($data)
    {
        try {
            $out_trade_no = $data['out_trade_no']??'';
            $total_amount = $data['total_amount']??'';
            $remark = $data['remark']??'';
            $device_id = $data['device_id']??'';
            $shop_name = $data['shop_name']??'';
            $notify_url = $data['notify_url']??''; //回调地址
            $url = $data['request_url']??'';  //正扫请求三方地址
            $payType = $data['pay_type']??'';
            $mer_cust_id = $data['mer_cust_id']??'';
            $org_id = $data['org_id']??'';
            $private_key = $data['private_key']??'';
            $public_key = $data['public_key']??'';
            $user_cust_id = $data['user_cust_id']??'';
            $user_id_query_url = $data['user_id_query_url']??''; //获取用户信息请求地址
            $auth_code = $data['auth_code']??''; //用户授权码

            //获取微信、支付宝、银联正扫支付时的用户id
            $sign_data_query = [
                'api_version' => '20', //可选,版本号,目前固定为20
                'device_id' => $device_id, //设备号
                'cust_id' => $user_cust_id, //用户客户号
                'pay_type' => $payType=='ALIPAY'?'A1':($payType=='WECHAT'?'W1':'U1'), //支付类型,A1-支付宝正扫;W1-微信正扫;U1-银联正扫
                'auth_code' => $auth_code, //授权码
                'union_app_identifier' => '', //可选,银联APP标识,不传默认CloudPay
                'mer_priv' => '', //可选,商户的私有数据项,原样返回
                'extension' => '', //可选,扩展域,原样返回
            ];
            $post_data_query = [
                'data'=> $sign_data_query,
                'sign_type'=> 'RSA2',
                'mer_cust_id'=> $mer_cust_id,
                'source_num'=> $org_id
            ];
            $result = $this->execute($user_id_query_url, $post_data_query, $sign_data_query, $private_key, $public_key);
            if ($result['status'] === '0') {
                return json_encode([
                    'status' => '0',
                    'message' => '系统错误'
                ]);
            }
            if ($result['status'] != '000000') {
                return json_encode([
                    'status' => '3',
                    'message' => $result['message']
                ]);
            } else {
                if ((isset($result['data'])) && (!empty($result['data']))) {
                    $return_data = json_decode($result['data'], true);

                    $sign_data = [
                        'api_version' => '20', //可选,版本号,目前固定为20
                        'device_id' => $device_id, //设备号
                        'cust_id' => $user_cust_id, //用户客户号
                        'pay_type' => $return_data['pay_type']??'', //支付类型,A1-支付宝正扫;W1-微信正扫;U1-银联正扫
                        'trans_amt' => number_format($total_amount, 2, '.', ''), //交易金额,泛指交易金额，金额格式必须是###.00，比如2.00，2.01
                        'order_id' => $out_trade_no, //订单号
                        'ip_addr' => get_client_ip(), //ip地址
                        'ret_url' => '', //页面回调地址,交易完成后渠道跳转的地址??
                        'oper_user_id' => '', //可选,操作员
                        'goods_desc' => '', //可选,商品描述
                        'os_version' => '', //可选,操作系统版本
                        'soft_version' => '', //可选,软件版本
                        'longitude' => '', //可选,经度
                        'latitude' => '', //可选,纬度
                        'imei' => '', //可选,imei
                        'mac_ip' => '', //可选,Mac地址
                        'bg_ret_url' => $notify_url, //可选,交易结果通知地址,不传则不通知,接口同步返回不通知
                        'mer_priv' => '', //可选,商户的私有数据项,原样返回
                        'extension' => '', //可选,扩展域,原样返回
                        'hb_fq_num' => '', //可选,用户花呗分期数,支付宝花呗分期分期数，暂时只支持3、6、12 ???
                        'is_raw' => '', //可选,微信公众号是否原生态,1-是;0-否;不填默认1
                    ];
                    if ($payType == 'ALIPAY') {
                        $sign_data['buyer_id'] = $return_data['buyer_id']??''; //买家的支付宝用户ID,支付宝支付时必须
                        $sign_data['buyer_logon_id'] = $return_data['buyer_logon_id']??''; //买家支付宝账号,支付宝支付时必须
                    } elseif ($payType == 'WECHAT') {
                        $sign_data['open_id'] = $return_data['open_id']??''; //微信用户关注商家公众号的openid,微信支付时必须
                    } else {
                        $sign_data['union_user_id'] = $return_data['union_user_id']??''; //银联用户标识,银联支付时必须
                    }
                    $post_data = [
                        'data'=> $sign_data,
                        'sign_type'=> 'RSA2',
                        'mer_cust_id'=> $mer_cust_id,
                        'source_num'=> $org_id
                    ];
                    $re = $this->execute($url, $post_data, $sign_data, $private_key, $public_key);

                    //系统错误
                    if ($re['status'] === '0') {
                        return json_encode([
                            'status' => '0',
                            'message' => '系统错误'
                        ]);
                    }

                    //业务成功
                    if ($re['status'] == "000000") {
                        //交易成功
                        return [
                            'status' => 1,
                            'message' => '交易成功',
                            'data' => isset($re['data'])?json_decode($re['data'], true):'',
                        ];
                    } elseif($re['status'] == '000001') {
                        //交易处理中
                        return [
                            'status' => 2,
                            'message' => $re['message'],
                            'data' => isset($re['data'])?json_decode($re['data'], true):'',
                        ];
                    } else {
                        //交易失败
                        return [
                            'status' => 3,
                            'message' => $re['message']
                        ];
                    }
                } else {
                    return json_encode([
                        'status' => '3',
                        'message' => $result['message']
                    ]);
                }
            }
        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }


    //订单查询 0-系统错误 1-成功 2-处理中 3-失败 4.初始
    public function order_query($data)
    {
        try {
            $out_trade_no = $data['out_trade_no']; //系统订单号
            $url = $data['request_url']; //请求地址
            $mer_cust_id = $data['mer_cust_id']; //商户客户号
            $org_id = $data['org_id']; //机构号
            $private_key = $data['private_key']; //
            $public_key = $data['public_key']; //
            $cust_id = $data['cust_id']; //用户客户号
            $device_id = $data['device_id']; //机具id

            $sign_data = [
                'cust_id' => $cust_id, //小微客户号
                'device_id' => $device_id, //终端设备号
                'order_type' => 'P', //订单类型,P-支付;R-退款
                'order_id' => $out_trade_no, //可选,订单号,退款时必填
                'party_order_id' => '', //可选,第三方支付凭证号,支付时和订单号二选一必填
            ];
            $data = [
                'data'=> $sign_data,
                'sign_type'=> 'RSA2',
                'mer_cust_id'=> $mer_cust_id,
                'source_num'=> $org_id
            ];
            $re = $this->execute($url, $data, $sign_data, $private_key, $public_key);

            //系统错误
            if ($re['status'] === '0') {
                return $re;
            }
            //业务成功
            if ($re['status'] == "000000") {
                $return_data = json_decode($re['data'], true);
                if ($return_data['resp_code'] == '000000') {
                    //交易成功  I-初始;S-成功;F-失败;P-处理中
                    if ($return_data['trans_stat'] == "S") {
                        return [
                            'status' => 1,
                            'message' => '交易成功',
                            'data' => $return_data,
                        ];
                    } //处理中
                    elseif ($return_data['trans_stat'] == "P") {
                        return [
                            'status' => 2,
                            'message' => '交易处理中',
                            'data' => $return_data,
                        ];
                        //失败
                    } elseif ($return_data['trans_stat'] == "F") {
                        return [
                            'status' => 3,
                            'message' => '交易失败',
                            'data' => $return_data,
                        ];
                    } else {
                        return [
                            'status' => 4,
                            'message' => '交易初始',
                            'data' => $return_data,
                        ];
                    }
                } else {
                    return [
                        'status' => 0,
                        'message' => $return_data['resp_desc']
                    ];
                }

            } else {
                return [
                    'status' => 0,
                    'message' => $re['message']
                ];
            }

        } catch (\Exception $exception) {
            return [
                'status' => 0,
                'message' => $exception->getMessage(),
            ];
        }
    }


    //退款 0-系统错误 1-成功 2-退款中 3-失败
    public function refund($data)
    {
        try {
//            Log::info('汇付退款参数22');
//            Log::info($data);
            $out_trade_no = $data['out_trade_no'];
            $url = $data['request_url'];
            $mer_cust_id = $data['mer_cust_id'];
            $orgId = $data['org_id'];
            $privateKey = $data['private_key'];
            $publicKey = $data['public_key'];
            $refund_amount = $data['refund_amount'];
            $ip = get_client_ip();
            $device_id = $data['device_id'];
            $user_cust_id = $data['user_cust_id'];
            $bg_ret_url = $data['notify_url']; //交易回调地址
            $trade_no = $data['trade_no']; //支付订单号

            $sign_data = [
                'api_version' => '20', //可选,版本号,目前固定为20
                'cust_id' => $user_cust_id, //用户客户号
                'order_id' => $out_trade_no, //订单号
                'org_order_id' => '', //可选,原支付订单号,原交易商户订单号、第三方订单号、外部订单号必须填其中一个
                'party_order_id' => $trade_no, //可选,第三方订单号
                'out_trans_id' => '', //可选,外部订单号
                'device_id' => $device_id, //机具号
                'ip_addr' => $ip, //ip地址
                'refund_amt' => number_format($refund_amount, 2), //退款金额,泛指交易金额，金额格式必须是###.00，比如2.00，2.01
                'oper_user_id' => '', //可选,操作员
                'os_version' => '', //可选,操作系统版本
                'soft_version' => '', //可选,软件版本
                'longitude' => '', //可选,经度
                'latitude' => '', //可选,纬度
                'imei' => '', //可选,imei
                'mac_ip' => '', //可选,Mac地址
                'base_station_info' => '', //可选,基站信息
                'bg_ret_url' => $bg_ret_url, //可选,交易结果通知地址,不传则不通知,接口同步返回不通知
                'mer_priv' => '', //可选,商户私有域,为商户的自定义字段，该字段在交易完成后由本平台原样返回
                'extension' => '', //可选,扩展域,用于扩展请求参数
            ];

            $post_data = [
                'data'=> $sign_data,
                'sign_type'=> 'RSA2',
                'mer_cust_id'=> $mer_cust_id,
                'source_num'=> $orgId
            ];
            $re = $this->execute($url, $post_data, $sign_data,$privateKey, $publicKey);
//$re['data']=["bank_code":"000","bank_message":"成功","business_amt":"0.01","device_id":"SMSM34358719666880610","extension":"","mer_priv":"","order_id":"wxscan20200111111227572222825","org_order_id":"","party_order_id":"MCS0000001200111111228h1fxy8qkVx","pay_type":"W0","refund_amt":"0.01","refund_fee_amt":"0.00","refund_service_amt":"0.00"]

            //系统错误
            if ($re['status'] === '0') {
                return $re;
            }
            //退款成功
            if ($re['status'] == "000000") {
                if (isset($re['data']) && !empty($re['data'])) {
                    $return_data = json_decode($re['data'], true);
                    return [
                        'status' => 1,
                        'message' => '退款成功',
                        'data' => $return_data,
                    ];
                } else {
                    return [
                        'status' => 1,
                        'message' => '退款成功',
                    ];
                }
            } elseif($re['status'] == "000001") {
                //退款中
                if (isset($re['data']) && !empty($re['data'])) {
                    $return_data = json_decode($re['data'], true);
                    return [
                        'status' => 2,
                        'message' => '退款中',
                        'data' => $return_data,
                    ];
                } else {
                    return [
                        'status' => 2,
                        'message' => '退款中',
                    ];
                }
            } else {
                //退款失败
                return [
                    'status' => 3,
                    'message' => $re['message'],
                ];
            }
        } catch (\Exception $exception) {
            return ['status' => -1, 'message' => $exception->getMessage().$exception->getLine(),];
        }
    }


    //退款查询 0-系统错误 1-成功 2-正在退款 3-失败 4-初始
    public function refund_query($data)
    {
        try {
            $out_trade_no = $data['out_trade_no'];
            $url = $data['request_url'];
            $mer_cust_id = $data['mer_cust_id'];
            $org_id = $data['org_id'];
            $private_key = $data['private_key'];
            $public_key = $data['public_key'];
            $cust_id = $data['user_cust_id']; //用户客户号
            $device_id = $data['device_id'];

            $sign_data = [
                'cust_id' => $cust_id, //小微客户号
                'device_id' => $device_id, //终端设备号
                'order_type' => 'R', //订单类型,P-支付;R-退款
                'order_id' => $out_trade_no, //可选,订单号,退款时必填
                'party_order_id' => '', //可选,第三方支付凭证号,支付时和订单号二选一必填
            ];
            $data = [
                'data'=> $sign_data,
                'sign_type'=> 'RSA2',
                'mer_cust_id'=> $mer_cust_id,
                'source_num'=> $org_id
            ];
            $re = $this->execute($url, $data, $sign_data, $private_key, $public_key);

            //系统错误
            if ($re['status'] === '0') {
                return $re;
            }
            //业务成功
            if ($re['status'] == "000000") {
                if (isset($re['data']) && !empty($re['data'])) {
                    $return_data = json_decode($re['data'], true);

                    //查询成功  I-初始;S-成功;F-失败;P-处理中
                    if ($return_data['trans_stat'] == "S") {
                        return [
                            'status' => 1,
                            'message' => '退款成功',
                            'data' => $return_data,
                        ];
                    } elseif ($return_data['trans_stat'] == "P") {
                        //处理中
                        return [
                            'status' => 2,
                            'message' => '退款处理中',
                            'data' => $return_data,
                        ];
                    } elseif ($return_data['trans_stat'] == "F") {
                        //失败
                        return [
                            'status' => 3,
                            'message' => '退款失败',
                            'data' => $return_data,
                        ];
                    } elseif ($return_data['trans_stat'] == "I") {
                        return [
                            'status' => 4,
                            'message' => '交易初始',
                            'data' => $return_data,
                        ];
                    } else {
                        return [
                            'status' => '0',
                            'message' => $re['message']
                        ];
                    }
                } else {
                    return [
                        'status' => '0',
                        'message' => $re['message']
                    ];
                }
            } else {
                return [
                    'status' => '0',
                    'message' => $re['message']
                ];
            }

        } catch (\Exception $exception) {
            return ['status' => '0', 'message' => $exception->getMessage(),];
        }
    }


}
